import java.io.*;
import java.util.*;
import com.aliasi.classify.*; 

public class VotingClassifier implements ConditionalClassifier<CharSequence> {

  private ConditionalClassifier<CharSequence> models[];

  private double weights[];
  
  public VotingClassifier ( ConditionalClassifier<CharSequence> models[] , double weights[] ) { 
	if ( weights.length != models.length || weights.length == 0 || models.length == 0 ) throw new IllegalArgumentException("Illegal arguments to voting classifier.");
	this.models = models; 
	this.weights = weights; 
  }
    
  public ConditionalClassification classify(CharSequence input) throws IllegalArgumentException {
	Map<String,Double> scores = new HashMap<String,Double>();
	ConditionalClassification c[] = new ConditionalClassification[models.length];
	int i = 0;
	for ( ConditionalClassifier<CharSequence> model : models ) c[i++] = model.classify(input);
	for ( ConditionalClassification result : c ) {
		for ( int rank = 0; rank < result.size(); rank++ ) {
			String cl = result.category(rank);
			double score = 0;
			for ( i = 0; i < c.length; i++) score += c[i].conditionalProbability(cl) * weights[i];
			scores.put(cl,score);		
	        }
	}
	String categories[] = scores.keySet().toArray(new String[0]);
	double conditionalProbs[] = new double[categories.length];
	for ( i=0; i<conditionalProbs.length; i++ ) conditionalProbs[i] = scores.get(categories[i]);
	return new ConditionalClassification(categories,conditionalProbs);
  } 

}
